<template>
  <div class="avatar-container">
    <div class="avatar-card-container">
      <el-avatar :size="50" :src="useUserStore().userInfo.avatarUrl" @mouseenter="showPopover = true" @mouseleave="startLeaveTimer" />
      <transition name="popup-fade" @before-enter="beforeEnter" @after-leave="afterLeave">
        <el-card class="popover-card" v-show="showPopover" shadow="hover" @mouseenter="cancelLeaveTimer"
          @mouseleave="startLeaveTimer">
          <div class="card-content">
            <div class="user-info">
              <h3>{{ nickname }}</h3>
              <el-button type="primary" size="small" @click="showUserCenter = true">
                个人中心
              </el-button>
            </div>

            <div class="history-list">
              <h4>历史规划</h4>
              <el-scrollbar height="200px">
                <div v-for="(item, index) in historyList" :key="index" class="history-item"
                  @click="handleHistoryClick(item)">
                  <div class="history-item-content">
                    <span class="plan-name">{{ item.planName }}</span>
                    <el-tag size="small" :type="getStatusType(item.status)">
                      {{ item.status }}
                    </el-tag>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </el-card>
      </transition>

      <el-dialog v-model="showUserCenter" title="个人中心" width="800px" :close-on-click-modal="false" destroy-on-close
        center>
        <UserCenter />
      </el-dialog>
    </div>

    <el-dialog v-model="showImportDialog" title="导入确认" width="400px" center class="import-dialog">
      <div class="import-content">
        <el-icon class="warning-icon">
          <Warning />
        </el-icon>
        <div class="import-message">
          <h4>确定导入此规划？</h4>
          <p class="sub-text">导入后将覆盖当前内容，此操作不可撤销</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirmImport">确定导入</el-button>
          <el-button @click="showImportDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import UserCenter from '@/components/user/UserCenter.vue'
import { useUserStore } from '@/stores/UserStore'
import { downloadUserAvatarByUserId } from '@/api/User'
import { getTravelPlanByUserId } from '@/api/TravelPlan'
import {Warning} from '@element-plus/icons-vue'
const userStore = useUserStore()
const showPopover = ref(false)
const showUserCenter = ref(false)
const historyList = ref([])
const showImportDialog = ref(false)
const selectedPlan = ref(null)
let leaveTimer = null
const emit = defineEmits(['import-plan'])

// 计算用户昵称
const nickname = computed(() => {
  return userStore.userInfo?.username || '未设置昵称'
})

//将 Base64 字符串转换为 Blob
function base64ToBlob(base64String) {
  const byteCharacters = atob(base64String);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: 'image/png' });
}


// 获取用户头像
const fetchUserAvatar = async () => {
  if (!userStore.userInfo?.userId) return
  try {
    const res = await downloadUserAvatarByUserId(userStore.userInfo.userId)
    if (res.status === 'success' && res.data) {
      const blob = base64ToBlob(res.data)
      //这里更新user对象，保证在更新头像的时候背景后的头像同步更新
      useUserStore().userInfo.avatarUrl = URL.createObjectURL(blob)
    }
  } catch (error) {
    console.error('获取头像失败:', error)
    // 使用默认头像
    useUserStore().userInfo.avatarUrl = new URL('@/assets/avator.png', import.meta.url).href
  }
}

const startLeaveTimer = () => {
  leaveTimer = setTimeout(() => {
    showPopover.value = false
  }, 200)
}

const cancelLeaveTimer = () => {
  if (leaveTimer) {
    clearTimeout(leaveTimer)
    leaveTimer = null
  }
}

const afterLeave = () => {
  const popover = document.querySelector('.popover-card')
  if (popover) {
    popover.style.transform = 'translateX(-50%)'
    popover.style.left = 'calc(50% - 100px)'
    popover.style.right = 'auto'
  }
}

const adjustPopoverPosition = () => {
  const popover = document.querySelector('.popover-card')
  if (!popover) return

  const viewportWidth = window.innerWidth
  const cardRect = popover.getBoundingClientRect()
  const rightSpace = viewportWidth - cardRect.right

  if (rightSpace < 20) {
    popover.style.left = 'auto'
    popover.style.right = '20px'
    popover.style.transform = 'none'
  }
}
// 获取历史规划列表
const fetchHistoryList = async () => {
  if (!userStore.userInfo?.userId) return
  try {
    const res = await getTravelPlanByUserId(userStore.userInfo.userId, 1, 10)
    if (res.status === 'success' && res.data) {
      historyList.value = res.data
    }
    console.log('历史规划列表:', historyList.value)
  } catch (error) {
    console.error('获取历史规划失败:', error)
  }
}

// 根据状态返回对应的类型
const getStatusType = (status) => {
  const statusMap = {
    'draft': 'info',
    'completed': 'success',
    'archived': 'warning'
    // 可以根据实际状态类型添加更多
  }
  return statusMap[status] || 'info'
}

// 处理历史项点击
const handleHistoryClick = (item) => {
  selectedPlan.value = item
  showImportDialog.value = true
}

const confirmImport = () => {
  if (selectedPlan.value) {
    // 发送导入事件,同时传递完整的规划信息
    emit('import-plan', {
      planId: selectedPlan.value.planId,
      planInfo: selectedPlan.value
    })
  }
  showImportDialog.value = false
  selectedPlan.value = null
}
// 在显示弹出卡片时获取历史规划
const beforeEnter = () => {
  nextTick(() => {
    adjustPopoverPosition()
    fetchHistoryList()
  })
}
onMounted(() => {
  fetchUserAvatar()
})
</script>

<style scoped>
.popup-fade-enter-active,
.popup-fade-leave-active {
  transition: all 0.25s ease-out;
}

.popup-fade-enter-from,
.popup-fade-leave-to {
  opacity: 0;
  transform: translateY(-5px);
}

.popup-fade-enter-to,
.popup-fade-leave-from {
  opacity: 1;
  transform: translateY(0);
}

.avatar-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.avatar-card-container {
  position: relative;
  display: inline-block;
}

.el-avatar {
  cursor: pointer;
}

.popover-card {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  width: 300px;
  border-radius: 12px;
  z-index: 1000;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.card-content {
  margin-top: 10px;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.user-info h3 {
  margin: 0;
  font-size: var(--el-font-size-large);
  color: var(--el-text-color-primary);
}

.history-list h4 {
  margin: 0 0 10px 0;
  font-size: var(--el-font-size-medium);
  color: var(--el-text-color-primary);
}

.history-item {
  padding: 10px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  cursor: pointer;
  color: var(--el-text-color-regular);
  transition: background-color 0.3s;
}

.history-item:hover {
  background-color: var(--el-fill-color-light);
}

.history-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.plan-name {
  flex: 1;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-tag {
  flex-shrink: 0;
}

.import-dialog :deep(.el-dialog__header) {
  padding: 15px 20px;
  margin-right: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.import-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 500;
}

.import-dialog :deep(.el-dialog__body) {
  padding: 25px 20px;
}

.import-content {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.warning-icon {
  font-size: 24px;
  color: var(--el-color-warning);
}

.import-message h4 {
  margin: 0 0 8px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.sub-text {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.dialog-footer {
  display: flex;
  justify-content: center; /* 改为居中对齐 */
  gap: 12px;
  width: 100%; /* 确保占满宽度 */
}
</style>